import { Component, OnInit } from '@angular/core';
import { ApiService } from '@core/services/http/api.service';
import { deepClone } from '../../../utils/utils';
import { ApesMessageService } from '@shared/apes/message';
import { GridConfigService } from '@core/config/grid-config.service';
import { GridOptions } from '@ag-grid-community/core';
import { ExpressionService } from '@core/services/expression/ExpressionService';
import { AllModules, Module } from '@ag-grid-enterprise/all-modules';

@Component({
  selector: 'ledger-form',
  templateUrl: './ledger-form.component.html',
  styleUrls: ['./ledger-form.component.scss'],
})
export class LedgerFormComponent implements OnInit {
  /** grid 相关 **/
  modules: Module[] = AllModules;
  rowData: any[] = [];
  rowDataItem: any[] = [];
  columnDefsMeteData: any[];
  columnDefsItemMeteData: any[];
  columnDefs: any = [];
  gridOptions: GridOptions;
  height: any = 200 + 'px';
  tabList: any = [];
  ctx = { model: {} };
  localeText: any;

  /** 按钮相关 **/
  buttonBar = [
    // {hide: true, style: 'default', label: '导出', id: 'action_export'},
    { hide: true, style: 'default', label: '查询', id: 'action_query', loading: false },
    // { hide: true, style: 'default', label: '重置', id: 'action_reset' },
    // { hide: true, style: 'default', label: '展开查询条件', id: 'action_show' },
  ];

  /** 明细数据查询条件 **/
  hind: string = 'none';     // 中间必填项
  timeList: any = [];       // 日期
  startValue: Date = null;
  endValue: Date = null;
  endDate = null;                     // 默认结束时间
  startDate = null;                   // 默认开始时间 当天
  itemsList = {};
  tabsId: string;

  /** 分页器 **/
  total = 0;
  pageSize = 50;
  currentPage = 0;

  /** 获取公司、部门、合作伙伴相关 **/
  hidn: string = 'none';            // 脑袋必填项
  company: any[];
  companyId: string = null;
  dept = [];
  deptId: string = null;
  partner = [];
  partnerObj :any;
  partnerId: string = null;
  partnerApi: any = 'cm.partyRole.findAll';

  constructor(private apiService: ApiService,
              private msg: ApesMessageService,
              private gridConfigService: GridConfigService,
              private expressionService: ExpressionService) {
    this.columnDefsMeteData = [
      {
        headerName: '公司代码',
        field: 'COMPANY_ID',
        width: 120,
        hide: true,
      },
      {
        headerName: '公司名称',
        field: 'COMPANY_NAME',
        width: 200,
        pinned: 'left',
      },
      {
        headerName: '部门代码',
        field: 'DEPT_ID',
        width: 200,
        hide: true,
      },
      {
        headerName: '部门名称',
        field: 'DEPT_NAME',
        width: 200,
        pinned: 'left',
      },
      {
        headerName: '合作伙伴代码',
        field: 'PARTNER_ID',
        width: 50,
        hide: true,
      },
      {
        headerName: '合作伙伴名称',
        field: 'PARTNER_NAME',
        width: 150,
        pinned: 'left',
      },
      {
        headerName: '合作方式',
        field: 'COOPERATION',
        width: 150,
        pinned: 'left',
      },
      {
        headerName: 'INVENTORY_MODE',
        field: 'INVENTORY_MODE',
        width: 100,
        hide: true,
      },
      {
        headerName: 'ACCOUNTING_METHOD',
        field: 'ACCOUNTING_METHOD',
        width: 100,
        hide: true,
      },
    ];
    this.columnDefsItemMeteData = [
      {
        headerName: '入账日期',
        field: 'ACCOUNTING_DATE',
        width: 150,
      },
      {
        headerName: '发生额',
        field: 'INCURRED',
        width: 90,
        cellRenderer: this.toFixed,
      },
      {
        headerName: '余额',
        field: 'AMOUNT',
        width: 90,
        cellRenderer: this.toFixed,
      },
      {
        headerName: '来源单号',
        field: 'SOURCE',
        width: 100,
      },
      {
        headerName: '来源单据',
        field: 'SOURCE_BUSINESS_TYPE',
        width: 90,
        hide: true,
      },
      {
        headerName: '来源单据',
        field: 'SOURCE_BUSINESS_TYPE_NAME',
        width: 90,
      },
      {
        headerName: '源单号',
        field: 'ORIGIN',
        width: 90,
      },
      {
        headerName: '源单据',
        field: 'ORIGIN_BUSINESS_TYPE',
        width: 90,
        hide: true,
      },
      {
        headerName: '源单据',
        field: 'ORIGIN_BUSINESS_TYPE_NAME',
        width: 90,
      },
    ];
    this.localeText = gridConfigService.getLocaleText();
  }

  ngOnInit() {
    this.apiService.post('ledger.account.list', {}).subscribe(data => {
      let iLength = data.length;
      this.columnDefs = deepClone(this.columnDefsMeteData);
      this.tabList = [];
      for (let i = 0; i < iLength; i++) {
        this.dynamicField(data[i]);
        this.dynamicTab(data[i]);
      }
    });

    // 默认 请求 当天 数据
    this.endDate = new Date();
    this.startDate = new Date(this.endDate.getTime() - (365 * 24 * 60 * 60 * 1000));
    this.timeList.push(this.startDate);
    this.timeList.push(this.endDate);

    this.getCompany();
    // this.getDept();
    this.getPartner();

  }

  onPageIndexChange() {
    this.getTableTabData(this.itemsList);
  }

  onRowClick($event: any) {
    this.itemsList = $event.data;
    this.queryBtn();
  }

  /***
   * 数据格式化
   * @returns {string}
   */

  getDownFormatter(): string {
    return '\'[ \' + value.id + \' ]\' + \' \' + value.name';
  }

  getValueFormatter(): string {
    return '\'[ \' + value.id + \' ]\' + \' \' + value.name';
  }

  formatter(value: any, expression: string) {
    return this.expressionService.evaluate(expression, {
      context: {},
      model: {},
      value: value,
    });
  }

  partnerDomain() {
    let domain = {
      'filters': [
        {
          'field': 'role.id',
          'operator': 'NE',
          'value': 'Employee',
        },
        {
          'field': 'party.partyType',
          'operator': 'NE',
          'value': 'person',
        },
      ],
      'groups': [
        {
          'filters': [
            {
              'field': 'id',
              'operator': 'EQ',
              'value': '{{value}}',
            },
            {
              'field': 'party.name',
              'operator': 'LIKE',
              'value': '{{value}}',
            },
          ],
          'groups': [],
          'operator': 'or',
        },
      ],
      'operator': 'and',
    };
    return domain;
  }

  customSearchFn(term: string, item: any) {
    term = term.toLowerCase();
    return item.name.toLowerCase().indexOf(term) > -1 || item.id.toLowerCase().indexOf(term) > -1;
  }

  dynamicField(item: any) {
    let field = {
      headerName: item.name,
      field: item.id,
      width: 120,
      cellRenderer: this.toFixed,
    };
    this.columnDefs.push(field);
  }

  dynamicTab(item: any) {
    let tab = {
      id: item.id,
      title: item.name,
      columnDefs: this.columnDefsItemMeteData,
    };
    this.tabList.push(tab);
    this.tabsId = this.tabList[0].id;
  }

  /**
   * 功能：按钮事件路由
   * @param data 当前按钮元数据
   */
  onEvent(data: any) {
    if (data instanceof MouseEvent) return;
    if (data) {
      if (data.id === 'action_query') {
        this.buttonBar[0].loading = true;
        this.action_query();
      }
      // else if (data.id === 'action_export') {
      //   this.action_export();
      // }
      // else if (data.id === 'action_show') {
      //   this.action_show();
      // } else if (data.id === 'action_reset') {
      //         this.action_reset();
      //       }
    }
  }

  /** 主数据 查询按钮事件 **/
  action_query() {
    if (this.companyId === null && this.deptId === null && this.partnerId === null) {
      this.hidn = 'block';
    } else {
      this.hidn = 'none';
      this.getTableFieldData();
    }
    this.buttonBar[0].loading = false;
  }

  /** 明细数据 查询按钮事件 **/
  queryBtn() {
    this.getDate(this.timeList, 'startValue', 'endValue');
    // 判断日期不能为空
    if (this.startValue === null) {
      this.hind = 'block';
    } else {
      this.hind = 'none';
    }
    //  必须满足以下条件才能调用接口
    if (this.hind === 'none') {
      this.getTableTabData(this.itemsList);
    }
  }

  /** 点击tab页签触发的事件 **/
  tabChanges(tabId: any) {
    this.currentPage = 0;
    this.tabsId = tabId;
    this.getTableTabData(this.itemsList);
  }

  /** 日期转换 **/
  getDate(time: any[], time_ks: string, time_js: string) {
    // debugger;
    let [first, second] = time;
    if (first) {
      this[time_ks] = first.toISOString().slice(0, 10);
    } else {
      this[time_ks] = null;
    }

    if (second) {
      this[time_js] = second.toISOString().slice(0, 10);
    } else {
      this[time_js] = null;
    }

  }

  /** 主表数据 **/
  getTableFieldData() {
    let data = { 'COMPANY_ID': this.companyId, 'PARTNER_ID': this.partnerId };  //, 'DEPT_ID': this.deptId
    this.apiService.post('ledger.main.list', { 'body': JSON.stringify(data) }).subscribe(data => {
      if (data) {
        this.rowData = data;
        if (this.rowData.length === 0) {
          this.msg.info(`未找到满足条件的数据`);
        }
      } else {
        this.msg.info(data.msg);
      }
    });
  }

  /** 明细数据 **/
  getTableTabData(list: any) {
    // this.rowDataItem = [];
    let data = {
      'customQuery': false,
      'queryid': 'ledger.items', 'page': this.currentPage, 'size': this.pageSize,
      'LEDGER_ACCOUNT_ID': this.tabsId,
      'ACCOUNTING_DATE_BEGIN': this.startValue, 'ACCOUNTING_DATE_END': this.endValue,
      'COMPANY_ID': list.COMPANY_ID, 'DEPT_ID': list.DEPT_ID, 'PARTNER_ID': list.PARTNER_ID,
      'INVENTORY_MODE': list.INVENTORY_MODE, 'ACCOUNTING_METHOD': list.ACCOUNTING_METHOD,
    };
    this.apiService.post('pub.query', { 'body': JSON.stringify(data) }).subscribe(data => {
      if (data) {
        this.total = data.total;
        this.rowDataItem = data.content;
        if (this.rowDataItem.length === 0) {
          this.msg.info(`未找到满足条件的数据`);
        }
      } else {
        this.msg.info(data.msg);
      }
    });
  }

  /** 获取 公司 **/
  getCompany() {
    let data = { 'pages': 1, 'size': 5000 };
    this.apiService.post('cm.company.find', { 'body': JSON.stringify(data) }).subscribe(
      (body) => {
        if (body) {
          this.company = body.content;
        } else {
          this.msg.info(body.msg);
        }
      });
  }

  /** 获取 部门 **/
  getDept() {
    let data = { 'pages': 1, 'size': 5000 };
    this.apiService.post('cm.dept.findAll', { 'body': JSON.stringify(data) }).subscribe(
      (body) => {
        if (body) {
          this.dept = body.content;
        } else {
          this.msg.info(body.msg);
        }
      });
  }

  /** 获取 合作伙伴 **/
  getPartner() {
    let data = { 'pages': 1, 'size': 5000 };
    this.apiService.post('cm.partyRole.findSupplierAndCorporateCustomer', { 'body': JSON.stringify(data) }).subscribe(
      (body) => {
        if (body) {
          this.partner = body.content;
        } else {
          this.msg.info(body.msg);
        }
      });
  }

  /** 保留两位小数点 **/
  toFixed(params) {
    let key = params.colDef.field;
    let data = params.data[key];
    if (data !== undefined) {
      data = data.toFixed(2);
    }
    return data;
  }

  checkData(param) {
    if (param) {
      this.partnerId = param.id;
    }
  }
}

